<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message, Modal } from '@arco-design/web-vue'
import { 
  getDishCategoryByMerchantId, 
  getDishByMerchantId,
  type Dish, 
  type DishCategory 
} from '@/api/dish'
import type { OrderItem } from '@/api/order'

const route = useRoute()
const router = useRouter()
const merchantId = computed(() => Number(route.params.id))
const loading = ref(false)
const dishCategories = ref<DishCategory[]>([])
const dishes = ref<Record<number | string, Dish[]>>({})
const recommendedDishes = ref<Dish[]>([])
const specialDishes = ref<Dish[]>([])
const activeCategoryId = ref<number | string>('recommended')
const cartItems = ref<OrderItem[]>([])
const cartVisible = ref(false)

// 计算购物车总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    const dish = findDishById(item.dishId)
    if (dish) {
      return total + (dish.isSpecial ? (dish.specialPrice || dish.price) : dish.price) * item.quantity
    }
    return total
  }, 0)
})

// 计算购物车商品总数
const totalQuantity = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 初始化数据
onMounted(async () => {
  loading.value = true
  try {
    // 获取菜品分类
    const categoriesRes = await getDishCategoryByMerchantId(merchantId.value)
    if (categoriesRes.code === 200 && categoriesRes.data) {
      dishCategories.value = categoriesRes.data
      console.log('成功获取菜品分类:', dishCategories.value)
    } else {
      console.warn('获取菜品分类失败:', categoriesRes.message)
    }
    
    // 获取所有菜品
    const dishesRes = await getDishByMerchantId(merchantId.value)
    if (dishesRes.code === 200 && dishesRes.data) {
      // 将菜品按分类整理
      const allDishes = dishesRes.data
      console.log('成功获取所有菜品:', allDishes)
      
      // 获取推荐菜品
      recommendedDishes.value = allDishes.filter(dish => dish.isRecommended === 1)
      dishes.value['recommended'] = recommendedDishes.value
      console.log('推荐菜品:', recommendedDishes.value)
      
      // 获取特价菜品
      specialDishes.value = allDishes.filter(dish => dish.isSpecial === 1)
      dishes.value['special'] = specialDishes.value
      console.log('特价菜品:', specialDishes.value)
      
      // 按分类整理菜品
      dishCategories.value.forEach(category => {
        dishes.value[category.id] = allDishes.filter(dish => dish.categoryId === category.id)
      })
    } else {
      console.warn('获取所有菜品失败:', dishesRes.message)
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    Message.error('加载数据失败，请稍后再试')
  } finally {
    loading.value = false
  }
  
  // 从localStorage加载购物车数据
  const cartData = localStorage.getItem(`cart_${merchantId.value}`)
  if (cartData) {
    try {
      cartItems.value = JSON.parse(cartData)
    } catch (e) {
      console.error('解析购物车数据失败:', e)
    }
  }
})

// 切换分类
const handleCategoryChange = async (categoryId: number | string) => {
  activeCategoryId.value = categoryId
}

// 根据ID查找菜品
const findDishById = (dishId: number): Dish | undefined => {
  for (const categoryDishes of Object.values(dishes.value)) {
    const dish = categoryDishes.find(d => d.id === dishId)
    if (dish) return dish
  }
  return undefined
}

// 添加到购物车
const addToCart = (dish: Dish) => {
  const existingItem = cartItems.value.find(item => item.dishId === dish.id)
  if (existingItem) {
    existingItem.quantity++
  } else {
    cartItems.value.push({
      dishId: dish.id,
      quantity: 1
    })
  }
  
  // 保存到localStorage
  localStorage.setItem(`cart_${merchantId.value}`, JSON.stringify(cartItems.value))
  
  // 保存一些基本的商家信息到localStorage，以便在购物车页面使用
  const merchantInfo = {
    id: merchantId.value,
    name: dish.merchantId ? `商家${dish.merchantId}` : `商家${merchantId.value}`,
    deliveryFee: 0,
    minOrderAmount: 0
  }
  localStorage.setItem(`merchant_info_${merchantId.value}`, JSON.stringify(merchantInfo))
  
  // 保存菜品信息到localStorage，以便在购物车页面使用
  localStorage.setItem(`dish_info_${dish.id}`, JSON.stringify(dish))
  
  Message.success('已添加到购物车')
}

// 从购物车移除
const removeFromCart = (dishId: number) => {
  const index = cartItems.value.findIndex(item => item.dishId === dishId)
  if (index !== -1) {
    if (cartItems.value[index].quantity > 1) {
      cartItems.value[index].quantity--
    } else {
      cartItems.value.splice(index, 1)
    }
    
    // 保存到localStorage
    localStorage.setItem(`cart_${merchantId.value}`, JSON.stringify(cartItems.value))
  }
}

// 清空购物车
const clearCart = () => {
  Modal.confirm({
    title: '确认清空购物车？',
    content: '清空后将无法恢复',
    onOk: () => {
      cartItems.value = []
      localStorage.removeItem(`cart_${merchantId.value}`)
      Message.success('购物车已清空')
    }
  })
}

// 去结算
const goToCheckout = () => {
  if (cartItems.value.length === 0) {
    Message.warning('购物车为空，请先添加商品')
    return
  }
  
  // 跳转到购物车页面
  router.push('/cart')
}
</script>

<template>
  <div class="merchant-detail-container">
    <a-spin :loading="loading" tip="加载中...">
      <!-- 菜品分类导航 -->
      <div class="category-nav">
        <a-scrollbar style="height: 60px">
          <div class="category-list">
            <a-tag
              checkable
              :checked="activeCategoryId === 'recommended'"
              @click="handleCategoryChange('recommended')"
              size="large"
            >
              推荐菜品
            </a-tag>
            <a-tag
              checkable
              :checked="activeCategoryId === 'special'"
              @click="handleCategoryChange('special')"
              size="large"
            >
              特价菜品
            </a-tag>
            <a-tag
              v-for="category in dishCategories"
              :key="category.id"
              checkable
              :checked="activeCategoryId === category.id"
              @click="handleCategoryChange(category.id)"
              size="large"
            >
              {{ category.name }}
            </a-tag>
          </div>
        </a-scrollbar>
      </div>

      <!-- 菜品列表 -->
      <div class="dish-list">
        <a-empty v-if="!dishes[activeCategoryId] || dishes[activeCategoryId].length === 0" description="暂无菜品" />
        <a-card
          v-for="dish in dishes[activeCategoryId]"
          :key="dish.id"
          class="dish-card"
          :bordered="false"
        >
          <div class="dish-info">
            <div class="dish-image">
              <img :src="'https://materials.cdn.bcebos.com/images/39275436/26649005146a34c5ba54ba695f238091.jpeg'" alt="菜品图片" />
              <div v-if="dish.isSpecial" class="dish-tag special">特价</div>
              <div v-if="dish.isRecommended" class="dish-tag recommended">推荐</div>
            </div>
            <div class="dish-details">
              <h3>{{ dish.name }}</h3>
              <p class="dish-desc">{{ dish.description }}</p>
              <div class="dish-price-actions">
                <div class="dish-price">
                  <span class="current-price">¥{{ dish.isSpecial ? (dish.specialPrice || dish.price) : dish.price }}</span>
                  <span v-if="dish.isSpecial" class="original-price">¥{{ dish.price }}</span>
                </div>
                <div class="dish-actions">
                  <a-button
                    type="primary"
                    shape="circle"
                    size="small"
                    @click="addToCart(dish)"
                  >
                    <template #icon><icon-plus /></template>
                  </a-button>
                </div>
              </div>
            </div>
          </div>
        </a-card>
      </div>

      <!-- 购物车浮动按钮 -->
      <div class="cart-button" @click="cartVisible = true">
        <a-badge :count="totalQuantity" :dot="false">
          <a-button shape="circle" size="large" type="primary">
            <template #icon><IconHeart/></template>
          </a-button>
        </a-badge>
        <span class="cart-price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>

      <!-- 购物车抽屉 -->
      <a-drawer
        v-model:visible="cartVisible"
        title="购物车"
        placement="bottom"
        height="60vh"
      >
        <div class="cart-content">
          <a-empty v-if="cartItems.length === 0" description="购物车为空" />
          <div v-else class="cart-items">
            <div v-for="item in cartItems" :key="item.dishId" class="cart-item">
              <div class="cart-item-info">
                <h4>{{ findDishById(item.dishId)?.name }}</h4>
                <div class="cart-item-price">
                  <span>¥{{ 
                    (findDishById(item.dishId)?.isSpecial 
                      ? (findDishById(item.dishId)?.specialPrice || findDishById(item.dishId)?.price) 
                      : findDishById(item.dishId)?.price) || 0 
                  }}</span>
                </div>
              </div>
              <div class="cart-item-actions">
                <a-button
                  shape="circle"
                  size="mini"
                  @click="removeFromCart(item.dishId)"
                >
                  <template #icon><icon-minus /></template>
                </a-button>
                <span class="cart-item-quantity">{{ item.quantity }}</span>
                <a-button
                  shape="circle"
                  size="mini"
                  @click="addToCart(findDishById(item.dishId)!)"
                >
                  <template #icon><icon-plus /></template>
                </a-button>
              </div>
            </div>
          </div>

          <div class="cart-footer">
            <div class="cart-total">
              <span>总计: ¥{{ totalPrice.toFixed(2) }}</span>
              <a-button type="text" status="danger" @click="clearCart">清空购物车</a-button>
            </div>
            <a-button
              type="primary"
              long
              size="large"
              :disabled="cartItems.length === 0"
              @click="goToCheckout"
            >
              {{ cartItems.length === 0 ? '购物车为空' : '去结算' }}
            </a-button>
          </div>
        </div>
      </a-drawer>
    </a-spin>
  </div>
</template>

<style scoped>
.merchant-detail-container {
  padding: 0 0 60px 0;
  max-width: 1200px;
  margin: 0 auto;
}

.category-nav {
  position: sticky;
  top: 0;
  z-index: 1;
  background-color: var(--bg-color-light);
  padding: 12px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid var(--border-color);
  box-shadow: var(--box-shadow-light);
}

.category-list {
  display: flex;
  gap: 12px;
  padding: 8px 16px;
}

.category-list .arco-tag {
  padding: 8px 16px;
  font-size: 16px;
  cursor: pointer;
}

.dish-list {
  padding: 0 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: flex-start;
}

.dish-card {
  margin-bottom: 0;
  border-radius: var(--border-radius-md);
  box-shadow: var(--box-shadow-light);
  transition: var(--transition-normal);
  overflow: hidden;
  width: calc(33.33% - 14px);
  min-width: 280px;
  flex-grow: 0;
}

.dish-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--box-shadow);
}

.dish-info {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.dish-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 0;
}

.dish-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.dish-card:hover .dish-image img {
  transform: scale(1.05);
}

.dish-tag {
  position: absolute;
  top: 12px;
  left: 12px;
  padding: 4px 10px;
  font-size: 14px;
  color: #fff;
  border-radius: var(--border-radius-sm);
  font-weight: bold;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.dish-tag.special {
  background-color: var(--danger-color);
}

.dish-tag.recommended {
  background-color: var(--warning-color);
}

.dish-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.dish-details h3 {
  font-size: 18px;
  font-weight: bold;
  margin: 0 0 10px 0;
  color: var(--text-primary);
}

.dish-desc {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0 0 16px 0;
  flex: 1;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dish-price-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.dish-price {
  display: flex;
  align-items: baseline;
  gap: 8px;
}

.current-price {
  font-size: 20px;
  font-weight: bold;
  color: var(--danger-color);
}

.original-price {
  font-size: 14px;
  color: var(--text-disabled);
  text-decoration: line-through;
}

.dish-actions .arco-btn {
  width: 36px;
  height: 36px;
  font-size: 18px;
}

.cart-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  background-color: var(--primary-color);
  padding: 12px 20px;
  border-radius: 30px;
  box-shadow: var(--box-shadow);
  color: white;
  cursor: pointer;
  transition: var(--transition-normal);
  z-index: 10;
}

.cart-button:hover {
  background-color: var(--primary-dark);
  transform: translateY(-2px);
}

.cart-price {
  font-weight: bold;
  font-size: 16px;
}

.cart-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 16px;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  border-radius: var(--border-radius-md);
  background-color: var(--bg-color-light);
  box-shadow: var(--box-shadow-light);
  transition: var(--transition-normal);
}

.cart-item:hover {
  box-shadow: var(--box-shadow);
}

.cart-item-info {
  flex: 1;
}

.cart-item-info h4 {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: var(--text-primary);
}

.cart-item-price {
  font-size: 16px;
  color: var(--danger-color);
  font-weight: 500;
}

.cart-item-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.cart-item-quantity {
  width: 30px;
  text-align: center;
  font-size: 16px;
  font-weight: 600;
}

.cart-footer {
  margin-top: 16px;
  padding: 20px 0;
  border-top: 1px solid var(--border-color);
}

.cart-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cart-total span {
  font-size: 18px;
  font-weight: bold;
}

.cart-total .arco-btn {
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .dish-card {
    width: calc(50% - 10px);
  }
}

@media (max-width: 768px) {
  .dish-card {
    width: 100%;
  }
}
</style> 